import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
    Button, Card, message, Modal,
} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';

import { ModelType } from './model';
import BasicInfoElem from './components/BasicInfoElem';
import CabinetInfoElem from './components/CabinetInfoElem';

import '@ant-design/compatible/assets/index.css';

interface saveAndEditProps extends FormComponentProps {
    dispatch: Dispatch;
    loading: boolean;
    campusCompanySaveAndEdit: ModelType;
    detailInfo: any;
    cabinetInfo: any;
    INITINFO: any;
    location: { query: any };
}

interface saveAndEditState {
    formValues: any;
}

@connect(
    ({
        campusCompanySaveAndEdit: { detailInfo, cabinetInfo },
        common: { INITINFO },
    }: any) => ({
        detailInfo,
        cabinetInfo,
        INITINFO,
    }),
)
class saveAndEditInfo extends Component<saveAndEditProps, saveAndEditState> {
    state: saveAndEditState = {
        formValues: {},
    };

    componentDidMount() {
        const {
            location: { query: { id } },
        } = this.props;
        if (id) this.fetchDetailInfo(id);

        this.fetchAction('common/fetchGardenType');
        this.fetchAction('common/fetchPassword');
        this.fetchAction('common/fetchAllOrgList');
        this.fetchAction('common/fetchTariffList');
        this.fetchAction('common/fetchAllProperty');
        this.fetchAction('common/fetchAddressList');
    }

    componentDidUpdate(prevProps: any) {
        const { location: { query: { id } } } = this.props;
        if (id && prevProps.location.query.id !== id) {
            this.fetchDetailInfo(id);
        }
    }

    componentWillUnmount() {
        this.fetchAction('clear');
    }

    fetchDetailInfo = (id: number) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'campusCompanySaveAndEdit/fetch',
            payload: { id, loadUser: 1 },
        });
    };

    handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        const { form: { validateFieldsAndScroll } } = this.props;
        validateFieldsAndScroll((errors, values) => {
            if (errors) return;

            const { longitude, latitude } = values;
            if (longitude.length > 16 || Number(longitude) < -180 || Number(longitude) > 180) {
                message.error('经度输入不正确');
            } else if (latitude.length > 16 || Number(latitude) < -90 || Number(latitude) > 90) {
                message.error('纬度输入不正确');
            }

            const { location: { query }, detailInfo } = this.props;
            if (query && query.id) values.id = query.id;

            const formValues = {
                ...values,
                userPickup: detailInfo.userPickup,
                pareaCode: values.areaGrop[0],
                careaCode: values.areaGrop[1],
                dareaCode: values.areaGrop[2],
                franchiseId: values.franchiseLabel ? values.franchiseLabel.key : 1,
                franchiseName: values.franchiseLabel ? values.franchiseLabel.label : '1',
                isEcEnabled: Number(values.isEcEnabled),
                isLetterEnabled: Number(values.isLetterEnabled),
            };
            delete formValues.franchiseLabel;
            delete formValues.areaGrop;

            this.setState({ formValues }, () => {
                Modal.confirm({
                    title: '确认提示',
                    icon: <ExclamationCircleOutlined />,
                    content: '保存前请检查所属部门、收费套餐等相关信息是否填写正确',
                    okText: '确认',
                    cancelText: '取消',
                    onOk: this.handleConfirmSubmit,
                });
            });
        });
    };

    handleConfirmSubmit = () => {
        const { formValues } = this.state;
        this.fetchAction('saveOrUpdate', formValues);
    };

    fetchAction = (typeName: string, payload = {}) => {
        const type = typeName.indexOf('common') >= 0
            ? typeName : `campusCompanySaveAndEdit/${typeName}`;

        const { dispatch } = this.props;
        dispatch({ type, payload });
    };

    render() {
        const {
            form,
            location: { query: { id } },
            detailInfo,
            cabinetInfo,
            INITINFO,
        } = this.props;

        return (
            <Fragment>
                <PageHeader />

                <Form
                    hideRequiredMark
                    className="tableListForm"
                    onSubmit={this.handleSubmit}
                >
                    <BasicInfoElem
                        forms={form}
                        detailInfo={detailInfo}
                        initInfo={INITINFO}
                        fetchAction={this.fetchAction.bind(this)}
                    />
                    {id && <CabinetInfoElem
                        detailInfo={detailInfo}
                        cabinetInfo={cabinetInfo}
                    />}

                    <Card bordered={false}>
                        <Button
                            type="primary"
                            htmlType="submit"
                        >
                            保存
                        </Button>
                        <Button
                            ghost
                            type="primary"
                            className="marginL16"
                            onClick={() => router.goBack()}
                        >
                            取消
                        </Button>
                    </Card>
                </Form>
            </Fragment>
        );
    }
}

export default Form.create<saveAndEditProps>()(saveAndEditInfo);
